/**
 * File    : MessageFormatBindingFactory.java
 * Created : 2008-10-19
 * By      : LuHuiguo
 */
package com.luhuiguo.tapestry.bindings;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.tapestry5.Binding;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.ioc.Location;
import org.apache.tapestry5.services.BindingFactory;
import org.apache.tapestry5.services.BindingSource;

/**
 * @author LuHuiguo
 * @version $Id: MessageFormatBindingFactory.java 16 2008-10-19 02:07:36Z LuHuiguo $
 * 
 */
public class MessageFormatBindingFactory implements BindingFactory {

	private final BindingSource bindingSource;

	public MessageFormatBindingFactory(BindingSource bindingSource) {
		this.bindingSource = bindingSource;
	}

	public Binding newBinding(String description, ComponentResources container,
			ComponentResources component, String expression, Location location) {
		String messageKey = expression.substring(0, expression.indexOf('='));
		List<String> parts = Arrays.asList(expression.substring(
				expression.indexOf('=') + 1).split(","));

		ArrayList<Binding> bindings = new ArrayList<Binding>(parts.size());
		for (String part : parts) {
			String prefix = BindingConstants.PROP;
			part = part.trim();

			if ('\'' == part.charAt(0)
					&& '\'' == part.charAt(part.length() - 1)) {
				part = part.substring(1, part.length() - 1);
				prefix = BindingConstants.LITERAL;
			}

			bindings.add(bindingSource.newBinding(description, container,
					component, prefix, part, location));
		}

		boolean invariant = true;
		for (Binding binding : bindings) {
			if (!binding.isInvariant()) {
				invariant = false;
				break;
			}
		}

		return new MessageFormatBinding(location, messageKey, component
				.getMessages(), bindings, invariant);
	}

}
